package cn.iocoder.yudao.module.reading.controller.app.record;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.reading.controller.app.record.vo.ReadingRecordCreateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.record.vo.RecentReadingRespVO;
import cn.iocoder.yudao.module.reading.controller.app.record.vo.TodayReadingRespVO;
import cn.iocoder.yudao.module.reading.controller.app.record.vo.ReadingStatusRespVO;
import cn.iocoder.yudao.module.reading.controller.app.record.vo.ReadingHistoryRespVO;
import cn.iocoder.yudao.module.reading.controller.app.record.vo.ReadingStatsRespVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.record.ReadingRecordDO;
import cn.iocoder.yudao.module.reading.service.record.ReadingRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 用户 APP - 阅读记录
 *
 * @author 李晨
 */
@Tag(name = "用户 APP - 阅读记录")
@RestController
@RequestMapping("/reading/reading-records")
@Validated
@Slf4j
public class ReadingRecordController {

    @Resource
    private ReadingRecordService readingRecordService;

    @PostMapping("/save")
    @Operation(summary = "保存阅读记录")
    @PreAuthenticated
    public CommonResult<Long> saveReadingRecord(@Valid @RequestBody ReadingRecordCreateReqVO createReqVO) {
        Long userId = getLoginUserId();
        Long recordId = readingRecordService.createOrUpdateReadingRecord(userId, createReqVO);
        return success(recordId);
    }

    @GetMapping("/book/{bookId}")
    @Operation(summary = "获取绘本阅读记录")
    @PreAuthenticated
    public CommonResult<ReadingRecordDO> getReadingRecord(
            @Parameter(description = "绘本ID", required = true, example = "1") @PathVariable("bookId") Long bookId) {
        Long userId = getLoginUserId();
        ReadingRecordDO record = readingRecordService.getReadingRecord(userId, bookId);
        return success(record);
    }

    @GetMapping("/recent")
    @Operation(summary = "获取最近阅读记录")
    @PreAuthenticated
    public CommonResult<List<RecentReadingRespVO>> getRecentReading(
            @Parameter(description = "语言类型", example = "en") @RequestParam(value = "lang", required = false) String lang,
            @Parameter(description = "限制数量", example = "10") @RequestParam(value = "limit", required = false) Integer limit) {
        Long userId = getLoginUserId();
        List<RecentReadingRespVO> result = readingRecordService.getRecentReading(userId, lang, limit);
        // 转换URL字段
        if (result != null) {
            result.forEach(item -> {
                if (item != null) {
                    item.convertUrls();
                }
            });
        }
        return success(result);
    }

    @GetMapping("/today")
    @Operation(summary = "获取今日阅读记录")
    @PreAuthenticated
    public CommonResult<TodayReadingRespVO> getTodayReading() {
        Long userId = getLoginUserId();
        TodayReadingRespVO result = readingRecordService.getTodayReading(userId);
        // 转换URL字段
        if (result != null) {
            result.convertUrls();
        }
        return success(result);
    }

    @DeleteMapping("/recent/clear")
    @Operation(summary = "清空最近阅读记录")
    @PreAuthenticated
    public CommonResult<Boolean> clearRecentReading(
            @Parameter(description = "语言类型", example = "en") @RequestParam(value = "lang", required = false) String lang) {
        Long userId = getLoginUserId();
        readingRecordService.clearRecentReading(userId, lang);
        return success(true);
    }

    @GetMapping("/stats")
    @Operation(summary = "获取阅读统计数据")
    @PreAuthenticated
    public CommonResult<ReadingStatsRespVO> getReadingStats() {
        Long userId = getLoginUserId();
        log.info("获取阅读统计数据，用户ID: {}", userId);

        ReadingStatsRespVO result = readingRecordService.getReadingStatsDetail(userId);
        return success(result);
    }

    @GetMapping("/status/today")
    @Operation(summary = "检查今日阅读状态")
    @PreAuthenticated
    public CommonResult<ReadingStatusRespVO> getTodayReadingStatus() {
        Long userId = getLoginUserId();
        log.info("检查今日阅读状态，用户ID: {}", userId);

        ReadingStatusRespVO result = readingRecordService.getTodayReadingStatus(userId);
        return success(result);
    }

    @GetMapping("/history")
    @Operation(summary = "获取阅读记录列表")
    @PreAuthenticated
    public CommonResult<List<ReadingHistoryRespVO>> getReadingHistory(
            @Parameter(description = "页码", example = "1") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页数量", example = "20") @RequestParam(value = "size", defaultValue = "20") Integer size,
            @Parameter(description = "语言类型", example = "en") @RequestParam(value = "lang", required = false) String lang) {
        Long userId = getLoginUserId();
        log.info("获取阅读记录列表，用户ID: {}, 页码: {}, 每页数量: {}, 语言: {}", userId, page, size, lang);

        List<ReadingHistoryRespVO> result = readingRecordService.getReadingHistory(userId, page, size, lang);
        // 转换URL字段
        if (result != null) {
            result.forEach(item -> {
                if (item != null) {
                    item.convertUrls();
                }
            });
        }
        return success(result);
    }

    @DeleteMapping("/{recordId}")
    @Operation(summary = "删除单条阅读记录")
    @PreAuthenticated
    public CommonResult<Boolean> deleteReadingRecord(
            @Parameter(description = "阅读记录ID", required = true, example = "1") @PathVariable("recordId") Long recordId) {
        Long userId = getLoginUserId();
        log.info("删除阅读记录，用户ID: {}, 记录ID: {}", userId, recordId);

        readingRecordService.deleteReadingRecord(userId, recordId);
        return success(true);
    }

    @DeleteMapping("/clear")
    @Operation(summary = "清空所有阅读记录")
    @PreAuthenticated
    public CommonResult<Boolean> clearAllReadingRecords() {
        Long userId = getLoginUserId();
        log.info("清空所有阅读记录，用户ID: {}", userId);

        readingRecordService.clearAllReadingRecords(userId);
        return success(true);
    }

}
